#include "lm_color.h"

static struct lm_color_pair_info color_pair_manager[256] = 
{
    [0].use_flag = 1,
};

uint16_t lm_rgb_convert_color_index(uint8_t red, uint8_t green, uint8_t blue)
{
    uint16_t color_index;
    color_index = 256 + ((blue>>5)<<6)  + ((green>>5)<<3) + (red>>5);
    return color_index;
}


//color_index MIN=256 MAX=767
void lm_init_palette(void)
{
    short color_index = 256;
    short r = 0, g = 0, b = 0;
    for(; b < 256; b += 32) {
        for(g = 0; g < 256; g += 32) {
            for(r = 0 ; r < 256; r += 32) {
                init_color(color_index, (uint16_t)(r*3.9), (uint16_t)(g*3.9), (uint16_t)(b*3.9));
                color_index ++;
            }
        }
    }
}

short lm_color_pair_getfree(void)
{
    for(int i=0; i<256; i++) {
        if(!color_pair_manager[i].use_flag) {
            return i;
        }
    }
    return -1;
}

int lm_init_pair(short fg, short bg)
{
    short pair;
    for(int i = 0; i < 256; i++) {
        if(color_pair_manager[i].use_flag) {
            if((color_pair_manager[i].fg == fg) && (color_pair_manager[i].bg == bg)) {
                return i;
            }
        }
        else {
            color_pair_manager[i].use_flag = 1;
            pair = i;
            break;
        }
    }

    init_pair(pair, fg, bg);
    color_pair_manager[pair].fg = fg;
    color_pair_manager[pair].bg = bg;
    
    return pair;
}

short lm_pair_get_fg(short pair)
{
    return color_pair_manager[pair].fg;
}

short lm_pair_get_bg(short pair)
{
    return color_pair_manager[pair].bg;
}

int lm_color_swap(lm_color_t color)
{
    return lm_init_pair(color.rgb_bg_index, color.rgb_fg_index);
}
